import esbuild, { build } from 'esbuild';
import fs, { write } from 'fs';
import { rm, mkdir, readFile, writeFile, stat } from 'fs/promises';
import { basename, resolve, dirname } from 'path';

(async () => {
    const ctx = await esbuild.context({
        entryPoints: ['./src/index.ts', './public/index.html'],
        outdir: './dist/',
        bundle: true,
        minify: false,
        external: ['fs'],
        sourcemap: 'inline',
        plugins: [
            {
                name: 'html-loader',
                setup: (build) => {
                    build.onLoad({
                        filter: /\.html$/ 
                    }, async (args) => {
                        const outDir = build.initialOptions.outdir;
                        if(!fs.existsSync(outDir)) {
                            await mkdir(outDir);
                        }

                        const fileOriginPat = args.path;
                        let content = await readFile(fileOriginPat, 'utf-8');

                        const entryPoints = build.initialOptions.entryPoints;
                        let jsSrc = entryPoints[0].replace(/.ts$/, '.js');
                        let scriptDOM = `<script src="${jsSrc}"></script>`;
                        content += `\n ${scriptDOM}`;
                        
                        const fileName = basename(fileOriginPat);
                        const targetPath = resolve(outDir, fileName);
                        await writeFile(targetPath, content);

                        return {
                            contents: `export default ${JSON.stringify(fileName)}`
                        }
                    })
                }
            }
        ]
    });

    ctx.watch();

    const {host, port} = await ctx.serve({
        host: 'localhost',
        servedir: './dist'
    });

    console.log(`listen on http://${host}:${port}`);
})();